<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class SampleController extends CI_Controller    
{        
    
        
    public function index()
    {                                
        
        if(isset ($_REQUEST["code"]))
        {
            $this->user = $this->loginFB();
            if(!is_null($this->user))
            {
                $this->isLogin = true;
            }                
        }                                                
                
        $data = array("isLogin" => false, "user" => "{name:hanoway}");
        
        $this->load->view('view', $data);
    }
    
    
    private function loginFB()
    {
        $userFacebook = new UserFacebook();
        $tokenFacebook = $userFacebook->getTokenSite();
                
        if($tokenFacebook)
        {
            $user = $userFacebook->getUserInfoFacebook();                                

            if($user)
            {                    
                $user = json_decode($user);                                        

                $userDataBase = new UserModel();
                
                if($userDataBase->where("idfacebook", $user->id)->get()->exists())
                {
                    $userDataBase->update('lastaccess', date("Y-m-d H:i:s"));
                    $userDataBase->save();
                }
                                
                else
                {
                    $userDataBase->setIdfacebook($user->id);
                    $userDataBase->setEmailfacebook($user->email);
                    $userDataBase->setCreatedon(date("Y-m-d H:i:s"));
                    $userDataBase->setLastaccess(date("Y-m-d H:i:s"));
                    $userDataBase->save();
                }

                $userSession = new UserSession();
                $userSession->setIdUser($userDataBase->getId());
                $userSession->setIdFB($user->id);
                $userSession->setNameFB($user->first_name);
                $userSession->setTokenFB($tokenFacebook);
                $userSession->setReadPermissionFB($userFacebook->readPermission($user->id));
                $userSession->setEmailFB($user->email);
                ($userDataBase->getName())?($userSession->setIsRegister(true)):($userSession->setIsRegister(false));
                
                $param = array('agx_user_toddynho'  => $userSession);

                helpSDT::sessions('agx_user_toddynho', $param);

                
                return $userSession;                                
            }        
        }
        
        return null;
    }  
}